<?php

namespace Helpers;

use Admin\Models\group\XhsysGrouppower;
use Admin\Models\group\XhsysGroupuser;
use Admin\Models\user\XhsysUser;
use Modules\Power;
use Modules\School;
use Phalcon\Di;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\user\XhsysUserpower;

class UserPower{

    public static function getSessionObject($name = null)
    {
        $session = Di::getDefault()->get('session');
        return $name ? $session->get($name) : $session;
    }


    /**
     * #方法说明：
     * @param null $userId
     * @return array
     * Created by zsc
     */
//    public static function getInterfaceUserPowerTags($userId = null)
//    {
//            $powerTags = array();
//            if(!$userId)return $powerTags;
//            $userPower = XhsysUserpower::findFirst("iUPUserId = {$userId}");
//            if ($userPower) {
//                $powerTags = array_merge($powerTags, explode(',', $userPower->mUPowerTag));
//            }
//            //获取角色组
//            $groupIds = XhsysGroupuser::find([
//                'columns'    => 'iGroupId',
//                'conditions' => 'bDelete = 0 AND iUserId = :userId:',
//                'bind'       => ['userId' => $userId]
//            ])->toArray();
//            if ($groupIds) {
//                $groupIds = array_column($groupIds, 'iGroupId');
//                //获取权限
//                $groupPower = XhsysGrouppower::find([
//                    'columns'    => 'mPowerTag',
//                    'conditions' => 'bDelete = 0 AND iGroupId IN ({groupId:array})',
//                    'bind'       => ['groupId' => $groupIds]
//                ])->toArray();
//                $groupPower = array_column($groupPower, 'mPowerTag');
//                foreach ($groupPower as $power) {
//                    $powerTags = array_merge($powerTags, explode(',', $power));
//                }
//            }
//            return $powerTags;
//    }



    /**
     * 获取用户权限列表
     *
     * @param null $targetUserId
     * @return array
     *
     * create by ck 20171108
     */
//    public static function getUserPowerTags($targetUserId = null)
//    {
//        $session = self::getSessionObject();
//        if ($targetUserId) {
//            $userId    = $targetUserId;
//            $powerTags = [];
//        }
//        else {
//            $userId    = Main::getLoginUserInfo('userId');
//            $powerTags = $session->get('UserPowerList');
//        }
//        if(!$powerTags){
//            $powerTags = [];
//            $userPower = XhsysUserpower::findFirst("iUPUserId = {$userId}");
//            if ($userPower) {
//                $powerTags = array_merge($powerTags, explode(',', $userPower->mUPowerTag));
//            }
//            //获取角色组
//            $groupIds = XhsysGroupuser::find([
//                'columns'    => 'iGroupId',
//                'conditions' => 'bDelete = 0 AND iUserId = :userId:',
//                'bind'       => ['userId' => $userId]
//            ])->toArray();
//            if ($groupIds) {
//                $groupIds = array_column($groupIds, 'iGroupId');
//                //获取权限
//                $groupPower = XhsysGrouppower::find([
//                    'columns'    => 'mPowerTag',
//                    'conditions' => 'bDelete = 0 AND iGroupId IN ({groupId:array})',
//                    'bind'       => ['groupId' => $groupIds]
//                ])->toArray();
//                $groupPower = array_column($groupPower, 'mPowerTag');
//                foreach ($groupPower as $power) {
//                    $powerTags = array_merge($powerTags, explode(',', $power));
//                }
//            }
//            if ($userId == User::getId()) {
//                $session->set('UserPowerList', $powerTags);
//            }
//        }
//        return $powerTags;
//    }

    /**
     * 判断session中是否存在用户权限信息
     * 没有则根据用户获取拥有的权限tag，组成数组后存入session
     * 再判断传入tag是否存在与用户权限tag中，存在返回true，否则返回false
     *
     * @param $powerTag     --权限标识
     * @return bool         --是否有权限
     *
     * create by ck 20160914
     * modify by ck 20160930    session公共方法
     * modify by ck 20170405    直接使用权限tag判断
     * modify by ck 20171108    添加权限组判断
     */
    public static function checkUserPower($powerTag)
    {
        return Power::exist($powerTag);
//        if (User::isAdmin()) {
//            return true;
//        }
//        return in_array($powerTag, Power::getPowerTags());
//        return in_array($powerTag, self::getUserPowerTags());
//        $userId = Main::getLoginUserInfo('userId');
//        $powerTags = $session->get('UserPowerList');
//        if(!$powerTags){
//            $powerTags = [];
//            $userPower = XhsysUserpower::findFirst("iUPUserId = {$userId}");
//            if ($userPower) {
//                $powerTags = array_merge($powerTags, explode(',', $userPower->mUPowerTag));
//            }
//            //获取角色组
//            $groupIds = XhsysGroupuser::find([
//                'columns'    => 'iGroupId',
//                'conditions' => 'bDelete = 0 AND iUserId = :userId:',
//                'bind'       => ['userId' => $userId]
//            ])->toArray();
//            if ($groupIds) {
//                $groupIds = array_column($groupIds, 'iGroupId');
//                //获取权限
//                $groupPower = XhsysGrouppower::find([
//                    'columns'    => 'mPowerTag',
//                    'conditions' => 'bDelete = 0 AND iGroupId IN ({groupId:array})',
//                    'bind'       => ['groupId' => $groupIds]
//                ])->toArray();
//                $groupPower = array_column($groupPower, 'mPowerTag');
//                foreach ($groupPower as $power) {
//                    $powerTags = array_merge($powerTags, explode(',', $power));
//                }
//            }
//            $session->set('UserPowerList', $powerTags);
//        }
//        return in_array($powerTag, $powerTag);
    }

    /**
     * 根据学校ID检查是否有查看/管理权限，有管理权限默认拥有查看权限
     *
     * @param $schoolId
     * @param bool|false $manage
     * @return bool
     *
     * create by ck 20161011
     * modify by ck 20170417    检验方法更改
     */
//    public static function checkSchoolExtraPowerById($schoolId, $manage = false)
//    {
//        if (User::isAdmin()) {
//            return true;
//        }
////        if(Main::getLoginUserInfo('userType') == 8) {
////            return true;
////        }
//        $powerIds    = self::getExtraSchoolPower(User::getId());
//        if($powerIds['manage']['all'] == 'true' || in_array($schoolId, $powerIds['manage']['id'])){
//            return true;
//        }
//        if(!$manage && ($powerIds['view']['all'] == 'true' || in_array($schoolId, $powerIds['view']['id']))){
//            return true;
//        }
//        return false;
//    }

    /**
     * 根据用户ID获取学校管理权限，并保存到session
     *
     * @param $userId
     * @return array|bool
     *
     * create by ck 20170219
     * modify by ck 20180416    判断教师，添加教师所属学校id
     * modify by ck 20180425    员工则不判断教师
     */
    public static function getExtraSchoolPower($userId)
    {
        if(!$userId) {
            return false;
        }
        $session = self::getSessionObject();
        $powerIds = $session->get("extraSchoolPower[{$userId}]");
        if(!$powerIds){
            $userPower = XhsysUserpower::findFirst("iUPUserId = {$userId} AND bDelete = 0");
            if (!$userPower) {
                $powerIds = [
                    'view'  => ['id' => [], 'all' => 'false'],
                    'manage'=> ['id' => [], 'all' => 'false']
                ];
            }
            else {
                $powerIds     = [];
                $viewPower   = json_decode($userPower->sUExtraView, true);
                $managePower = json_decode($userPower->sUExtraManage, true);
                if(isset($managePower['school'])) {
                    if(isset($managePower['school']['id'])){
                        $managePower['school']['id'] = array_values(array_unique(explode(',', $managePower['school']['id'])));
                    }
                    $powerIds['manage'] = $managePower['school'];
                }
                if(isset($viewPower['school'])) {
                    if(isset($viewPower['school']['id'])) {
                        $viewPower['school']['id'] = array_values(array_unique(explode(',', $viewPower['school']['id'])));
                    }
                    $powerIds['view'] = $viewPower['school'];
                }
            }
            if (!User::isStaff($userId)) {
                $user = XhsysUser::findFirst($userId);
                if ($user->iUserType == 4) {
                    if (array_search($user->iSchoolId, $powerIds['view']['id']) === false) {
                        $powerIds['view']['id'][] = $user->iSchoolId;
                    }
                    if (array_search($user->iSchoolId, $powerIds['manage']['id']) === false) {
                        $powerIds['manage']['id'][] = $user->iSchoolId;
                    }
                }
            }
            $session->set("extraSchoolPower[{$userId}]", $powerIds);
        }
        return $powerIds;
    }

    /**
     * 获取用户允许查看的学校ID
     *
     * @param bool $withName
     * @param int|null $userId
     * @return array|bool
     *
     * create by ck 20170219
     * modify by ck 20170417    更改判断方法
     * modify by ck 20170420    添加参数，同时返回学校名称
     */
    public static function getAuthorizationSchool($withName = false, $userId = null)
    {
        return School::getPower($withName, $userId);

//        if(Main::getLoginUserInfo('userType') == 8) {
//            return true;
//        }
//        if (!$userId && Main::getLoginUserInfo('logonName') == 'admin') {
//            return true;
//        }
//        $powerIds = self::getExtraSchoolPower($userId ?: Main::getLoginUserInfo('userId'));
//        if(!$powerIds) {
//            return false;
//        }
//        if((isset($powerIds['manage']['all']) && $powerIds['manage']['all'] == 'true') || (isset($powerIds['view']['all']) && $powerIds['view']['all'] == 'true')){
//            return true;
//        }
//        $schoolIdArr = array_filter(array_unique(array_merge(
//            $powerIds['manage']['id'] ?: [],
//            $powerIds['view']['id']   ?: []
//        )));
//        if($withName){
//            $schoolArr = XhschoolInfo::getSchoolSupportArray();
//            $newSchoolArr = [];
//            foreach($schoolIdArr as $schId){
//                $newSchoolArr[$schId] = $schoolArr[$schId];
//            }
//            $schoolIdArr = $newSchoolArr;
//        }
//        return $schoolIdArr ?: false;
    }

    /**
     * 删除session权限
     *
     * @param $target
     * @param null $userId
     * @return bool
     *
     * create by ck 20180108
     */
    public static function delPowerCache($target, $userId = null)
    {
        if (!$userId) {
            $userId = Main::getLoginUserInfo('userId');
        }
        $session = self::getSessionObject();
        switch ($target) {
            case 'school': return $session->remove("extraSchoolPower[{$userId}]");
            default: return false;
        }
    }
    
}